<template>
  <div class="map-picker">
    <div class="map-search">
      <el-input
        v-model="address"
        placeholder="输入地址定位"
        clearable
        @keyup.enter="searchAddress"
      >
        <template #append>
          <el-button @click="searchAddress" :loading="searchLoading">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
    </div>
    
    <div id="map-container" class="map-container"></div>
    
    <div class="location-info" v-if="modelValue && modelValue.lat && modelValue.lng">
      <div class="location-item">
        <span class="location-label">经度：</span>
        <span class="location-value">{{ modelValue.lng.toFixed(6) }}</span>
      </div>
      <div class="location-item">
        <span class="location-label">纬度：</span>
        <span class="location-value">{{ modelValue.lat.toFixed(6) }}</span>
      </div>
      <div class="location-item" v-if="modelValue.address">
        <span class="location-label">地址：</span>
        <span class="location-value">{{ modelValue.address }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { AMapLoader } from '@amap/amap-jsapi-loader'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

// 状态
const address = ref('')
const searchLoading = ref(false)

// 地图实例
let mapInstance = null
let marker = null
let geocoder = null

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: '2bd1031aa08256eeba5539a5577c3ff7',
      version: '2.0',
      plugins: ['AMap.Geocoder', 'AMap.AutoComplete', 'AMap.PlaceSearch']
    })
    
    // 初始中心位置
    const defaultCenter = [116.397428, 39.90923]
    const center = props.modelValue && props.modelValue.lng && props.modelValue.lat
      ? [props.modelValue.lng, props.modelValue.lat]
      : defaultCenter
      
    // 创建地图实例
    mapInstance = new AMap.Map('map-container', {
      zoom: 13,
      center
    })
    
    // 创建地理编码器
    geocoder = new AMap.Geocoder({
      city: '全国'
    })
    
    // 创建标记（如果有初始位置）
    if (props.modelValue && props.modelValue.lng && props.modelValue.lat) {
      createMarker([props.modelValue.lng, props.modelValue.lat])
      address.value = props.modelValue.address || ''
    }
    
    // 只有非只读模式才添加点击事件
    if (!props.readonly) {
      mapInstance.on('click', (e) => {
        const lnglat = e.lnglat
        createMarker([lnglat.getLng(), lnglat.getLat()])
        reverseGeocode(lnglat)
      })
    }
    
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图加载失败，请检查API密钥设置')
  }
}

// 创建标记
const createMarker = (position) => {
  if (marker) {
    mapInstance.remove(marker)
  }
  
  marker = new AMap.Marker({
    position,
    draggable: !props.readonly,
    cursor: 'move',
    animation: 'AMAP_ANIMATION_DROP'
  })
  
  mapInstance.add(marker)
  mapInstance.setCenter(position)
  
  if (!props.readonly) {
    // 拖拽结束后更新位置
    marker.on('dragend', (e) => {
      const lnglat = e.target.getPosition()
      reverseGeocode(lnglat)
    })
  }
  
  // 更新数据
  emit('update:modelValue', {
    ...props.modelValue,
    lng: position[0],
    lat: position[1]
  })
}

// 地址搜索
const searchAddress = async () => {
  if (!address.value.trim()) {
    ElMessage.warning('请输入地址')
    return
  }
  
  searchLoading.value = true
  try {
    geocoder.getLocation(address.value, (status, result) => {
      searchLoading.value = false
      
      if (status === 'complete' && result.geocodes.length) {
        const location = result.geocodes[0].location
        createMarker([location.getLng(), location.getLat()])
        
        // 更新地址
        emit('update:modelValue', {
          ...props.modelValue,
          lng: location.getLng(),
          lat: location.getLat(),
          address: result.geocodes[0].formattedAddress
        })
        
        // 更新输入框
        address.value = result.geocodes[0].formattedAddress
      } else {
        ElMessage.warning('未找到该地址')
      }
    })
  } catch (error) {
    searchLoading.value = false
    console.error('地址搜索失败:', error)
    ElMessage.error('地址搜索失败')
  }
}

// 根据经纬度获取地址
const reverseGeocode = (lnglat) => {
  geocoder.getAddress(lnglat, (status, result) => {
    if (status === 'complete' && result.regeocode) {
      const addressInfo = result.regeocode.formattedAddress
      address.value = addressInfo
      
      // 更新数据
      emit('update:modelValue', {
        ...props.modelValue,
        lng: lnglat.getLng(),
        lat: lnglat.getLat(),
        address: addressInfo
      })
    } else {
      console.error('逆地理编码失败')
    }
  })
}

// 监听modelValue变化更新地图
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && newVal.lng && newVal.lat && mapInstance) {
      createMarker([newVal.lng, newVal.lat])
      address.value = newVal.address || ''
    }
  },
  { deep: true }
)

// 生命周期钩子
onMounted(() => {
  initMap()
  console.log('地图加载成功')
})

onUnmounted(() => {
  if (mapInstance) {
    mapInstance.destroy()
    mapInstance = null
  }
})
</script>

<style scoped>
.map-picker {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.map-search {
  margin-bottom: 10px;
}

.map-container {
  width: 100%;
  height: 400px;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
  border: 1px solid #dcdfe6;
}

.location-info {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.location-item {
  margin-bottom: 5px;
  display: flex;
}

.location-label {
  width: 50px;
  color: #606266;
}

.location-value {
  flex: 1;
  color: #303133;
  font-weight: 500;
}
</style>